<template>
  <div class="ai-chat-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="chat-card">
          <template #header>
            <div class="chat-header">
              <h2>智能健康助手 <small>(通义AI提供支持)</small></h2>
              <div>
                <el-tooltip content="切换咨询模式" placement="top">
                  <el-switch
                    v-model="isHealthMode"
                    active-text="健康咨询"
                    inactive-text="普通对话"
                    @change="handleModeChange"
                  />
                </el-tooltip>
                <el-button type="danger" size="small" @click="confirmClearHistory" plain>
                  清空历史
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 聊天内容区域 -->
          <div class="chat-content" ref="chatContent">
            <div v-if="chatHistory.length === 0" class="empty-chat">
              <el-empty description="暂无聊天记录" :image-size="120">
                <template #description>
                  <p>在下方输入框开始与AI助手对话吧！</p>
                  <p v-if="isHealthMode"><small>当前模式: 健康咨询</small></p>
                  <p v-else><small>当前模式: 普通对话</small></p>
                </template>
              </el-empty>
            </div>
            
            <div v-else class="chat-messages">
              <div v-for="chat in chatHistory" :key="chat.id" class="chat-item">
                <div class="user-message">
                  <div class="message-header">
                    <span class="username">我</span>
                    <span class="time">{{ formatTime(chat.created_at) }}</span>
                  </div>
                  <div class="message-content">{{ chat.message }}</div>
                </div>
                
                <div class="ai-message">
                  <div class="message-header">
                    <span class="username">智能助手</span>
                    <el-button 
                      type="danger" 
                      size="small" 
                      icon="Delete" 
                      circle 
                      plain
                      @click="deleteChat(chat.id)"
                    />
                  </div>
                  <div class="message-content" v-html="formatMessage(chat.response)"></div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 输入区域 -->
          <div class="chat-input">
            <el-input
              v-model="message"
              type="textarea"
              :rows="3"
              :placeholder="isHealthMode ? '请输入您的健康问题...' : '请输入您的问题...'"
              @keyup.enter.ctrl="sendMessage"
            />
            <div class="input-actions">
              <span class="tip">提示: 按Ctrl+Enter发送</span>
              <el-button 
                type="primary"
                :loading="loading" 
                @click="sendMessage"
                :disabled="!message.trim()"
              >
                发送
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AIChat',
  
  setup() {
    const store = useStore()
    const message = ref('')
    const isHealthMode = ref(true)
    const chatContent = ref(null)
    
    // 从store获取状态
    const chatHistory = computed(() => store.getters['chat/chatHistory'])
    const loading = computed(() => store.getters['chat/isLoading'])
    
    // 加载聊天历史
    onMounted(async () => {
      try {
        await store.dispatch('chat/loadChatHistory')
        scrollToBottom()
      } catch (error) {
        ElMessage.error('获取聊天历史失败')
      }
    })
    
    // 监听聊天历史变化，自动滚动到底部
    watch(chatHistory, () => {
      nextTick(() => {
        scrollToBottom()
      })
    })
    
    // 滚动到底部
    const scrollToBottom = () => {
      if (chatContent.value) {
        chatContent.value.scrollTop = chatContent.value.scrollHeight
      }
    }
    
    // 发送消息
    const sendMessage = async () => {
      if (!message.value.trim()) return
      
      try {
        if (isHealthMode.value) {
          await store.dispatch('chat/getHealthAdvice', message.value)
        } else {
          await store.dispatch('chat/sendMessage', message.value)
        }
        message.value = ''
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '发送消息失败')
      }
    }
    
    // 删除某条聊天记录
    const deleteChat = async (chatId) => {
      try {
        await store.dispatch('chat/deleteChat', chatId)
        ElMessage.success('删除成功')
      } catch (error) {
        ElMessage.error('删除失败')
      }
    }
    
    // 清空聊天历史
    const confirmClearHistory = () => {
      ElMessageBox.confirm('确定要清空所有聊天历史吗？此操作不可恢复。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await store.dispatch('chat/clearChatHistory')
          ElMessage.success('聊天历史已清空')
        } catch (error) {
          ElMessage.error('清空失败')
        }
      }).catch(() => {})
    }
    
    // 切换咨询模式
    const handleModeChange = () => {
      ElMessage.info(`已切换至${isHealthMode.value ? '健康咨询' : '普通对话'}模式`)
    }
    
    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 格式化消息，处理链接和换行
    const formatMessage = (text) => {
      if (!text) return ''
      // 将换行符转换为<br>
      let formatted = text.replace(/\n/g, '<br>')
      // 将URL转换为可点击的链接
      formatted = formatted.replace(
        /(https?:\/\/[^\s]+)/g, 
        '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>'
      )
      return formatted
    }
    
    return {
      message,
      isHealthMode,
      chatContent,
      chatHistory,
      loading,
      sendMessage,
      deleteChat,
      confirmClearHistory,
      handleModeChange,
      formatTime,
      formatMessage
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  padding: 20px;
}

.chat-card {
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.chat-header small {
  font-size: 0.8rem;
  color: #909399;
  font-weight: normal;
}

.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  margin-bottom: 10px;
}

.empty-chat {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chat-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.user-message, .ai-message {
  padding: 10px 15px;
  border-radius: 6px;
  max-width: 80%;
}

.user-message {
  align-self: flex-end;
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
}

.ai-message {
  align-self: flex-start;
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.username {
  font-weight: bold;
  color: #409eff;
}

.time {
  font-size: 0.8rem;
  color: #909399;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
}

.chat-input {
  margin-top: auto;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.tip {
  font-size: 0.8rem;
  color: #909399;
}

:deep(.message-content a) {
  color: #409eff;
  text-decoration: none;
}

:deep(.message-content a:hover) {
  text-decoration: underline;
}
</style> 